package com.pipi.biyesheji.controller;

import com.pipi.biyesheji.dao.support.PageResult;
import com.pipi.biyesheji.enums.AllEnums;
import com.pipi.biyesheji.pojo.Category;
import com.pipi.biyesheji.pojo.Role;
import com.pipi.biyesheji.pojo.User;
import com.pipi.biyesheji.service.impl.UserInfo;
import com.pipi.biyesheji.service.CategoryService;
import com.pipi.biyesheji.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品分类模块controller
 * @author pipi
 */
@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Resource
    private UserInfo userInfo;

    @Resource
    private RoleService roleService;

    @RequestMapping("/list")
    public String list(Model model){
        PageResult<Category> pageResult = categoryService.list(null);
        List<Category> categoryList = pageResult.getResult();

        User currentUser = userInfo.getCurrentUser();
        Role role = roleService.getRoleByUserId(currentUser.getId());
        if (Objects.equals(AllEnums.RoleEnum.BUSINESS.getName(), role.getName())) {
            categoryList = categoryList.stream().filter(category -> Objects.equals(category.getUserId(),
                    currentUser.getId())).collect(Collectors.toList());
        }
        model.addAttribute("list",categoryList);
        model.addAttribute("size",categoryList.size());
        return "productmodule/category-list";
    }

    @RequestMapping("/addCategory")
    public String add(@RequestParam(value = "name")String name){
        Category category = new Category();
        category.setName(name);
        category.setUserId(userInfo.getCurrentUser().getId());
        categoryService.save(category);
        return "productmodule/category-list";
    }

    @RequestMapping("/delCategory")
    public String del(@RequestParam(value = "id")Long id){
        categoryService.del(id);
        return "redirect:list";
    }

    @RequestMapping("/editCategory")
    public String edit(@RequestParam(value = "id")Long id,Model model){
        Category category = categoryService.get(id);
        model.addAttribute("category",category);
        return "productmodule/category-edit";
    }

    @RequestMapping("/updateCategory")
    public String update(Category category){
        categoryService.update(category);
        return "redirect:list";
    }

}
